﻿using Archives.Entities;
using Archives.IService;
using Archives.Models;
using Archives.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Archives.Service
{
    public class WorkflowQueryService : IWorkflowQueryService
    {
        private readonly IRepository _repository;
        
        public WorkflowQueryService(IRepository repository)
        {
            _repository = repository;
        }

        public WorkflowQueryModel GetWorkflowQueryInfo(WorkflowQuery query)
        {
            var data = from a in _repository.All<GW_ReceiveFile>(m=>m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                       join b in _repository.All<WKF_Message>(m=>m.MessageStatus != 3)
                       on a.MessageId equals b.MessageID
                       join c in _repository.All<ORG_Employee>()
                       on b.MessageIssuedBy equals c.EmplID
                       join d in _repository.All<ORG_Department>()
                       on b.MessageIssuedDept equals d.DeptID
                       select new WorkflowModel
                       {
                           MessageId = a.MessageId,
                           WorkFlowId = a.WorkFlowId,
                           ClosedOrHairTime = a.ClosedOrHairTime,
                           DocumentNumber = a.DocumentNumber,
                           DocumentTitle = a.DocumentTitle,
                           SequenceName = a.SequenceName,
                           SequenceNumber = a.SequenceNumber,
                           MessageIssuedBy = b.MessageIssuedBy,
                           MessageIssuedName = c != null ? c.EmplName : null,
                           MessageIssuedDept = b.MessageIssuedDept,
                           MessageIssuedDeptName = d != null ? d.DeptName : null,
                           MessageTitle = b.MessageTitle,
                           MessageStatus = b.MessageStatus,
                           MessageCreateTime = b.MessageCreateTime,
                           MessageStatusName = b.MessageStatus == 0 ? "草稿" : 
                                                    (b.MessageStatus == 1 ? "运行中" : 
                                                    (b.MessageStatus == 2 ? "已完成" :
                                                    (b.MessageStatus == 3 ? "终止信息" : null)))
                       };
            var draft = from a in _repository.All<GW_ReceiveFile>()
                        join b in _repository.All<WKF_Message>(m => m.MessageType == "file" && m.MessageStatus != 3)
                        on a.MessageId equals b.MessageID
                        join c in _repository.All<ORG_Employee>()
                        on b.MessageIssuedBy equals c.EmplID
                        join d in _repository.All<ORG_Department>()
                        on b.MessageIssuedDept equals d.DeptID
                        select new WorkflowModel
                        {
                            MessageId = a.MessageId,
                            WorkFlowId = a.WorkFlowId,
                            ClosedOrHairTime = a.ClosedOrHairTime,
                            DocumentNumber = a.DocumentNumber,
                            DocumentTitle = a.DocumentTitle,
                            SequenceName = a.SequenceName,
                            SequenceNumber = a.SequenceNumber,
                            MessageIssuedBy = b.MessageIssuedBy,
                            MessageIssuedName = c != null ? c.EmplName : null,
                            MessageIssuedDept = b.MessageIssuedDept,
                            MessageIssuedDeptName = d != null ? d.DeptName : null,
                            MessageTitle = b.MessageTitle,
                            MessageStatus = b.MessageStatus,
                            MessageCreateTime = b.MessageCreateTime,
                            MessageStatusName = b.MessageStatus == 0 ? "草稿" :
                                                     (b.MessageStatus == 1 ? "运行中" :
                                                     (b.MessageStatus == 2 ? "已完成" :
                                                     (b.MessageStatus == 3 ? "终止信息" : null)))
                        };
            data = data.Union(draft).Distinct();
            if (query.PageNumber <= 0)
            {
                query.PageNumber = 1;
            }
            if (query.PageSize <= 0)
            {
                query.PageSize = 20;
            }
            //流程类型
            if (!string.IsNullOrWhiteSpace(query.WorkFlowId))
            {
                data = data.Where(m => m.WorkFlowId == query.WorkFlowId);
            }
            //流程状态
            if (query.MessageStatus.HasValue)
            {
                data = data.Where(m => m.MessageStatus == query.MessageStatus.Value);
            }
            //开始收发文时间
            if (query.StartClosedOrHairTime.HasValue)
            {
                data = data.Where(m => m.ClosedOrHairTime >= query.StartClosedOrHairTime.Value);
            }
            //结束收发文时间
            if (query.EndClosedOrHairTime.HasValue)
            {
                data = data.Where(m => m.ClosedOrHairTime <= query.EndClosedOrHairTime.Value);
            }
            //来文号
            if (!string.IsNullOrWhiteSpace(query.DocumentNumber))
            {
                data = data.Where(m => m.DocumentNumber.Contains(query.DocumentNumber));
            }
            //收文序列
            if (!string.IsNullOrWhiteSpace(query.SequenceName))
            {
                data = data.Where(m => m.SequenceName == query.SequenceName);
            }
            //收文号
            if (!string.IsNullOrWhiteSpace(query.SequenceNumber))
            {
                data = data.Where(m => m.SequenceNumber.Contains(query.SequenceNumber));
            }
            //发起部门
            if (!string.IsNullOrWhiteSpace(query.MessageIssuedDept))
            {
                data = data.Where(m => m.MessageIssuedDept == query.MessageIssuedDept);
            }
            //发起人
            if (!string.IsNullOrWhiteSpace(query.MessageIssuedBy))
            {
                data = data.Where(m => m.MessageIssuedBy == query.MessageIssuedBy);
            }
            //模糊检索
            if (!string.IsNullOrWhiteSpace(query.QueryCondition))
            {
                data = data.Where(m => m.DocumentTitle.Contains(query.QueryCondition));
            }
            var result = new WorkflowQueryModel();
            //总数
            var totalRecouds = data.Count();
            //总页数
            var totalPages = totalRecouds % query.PageSize == 0 ? totalRecouds / query.PageSize : totalRecouds / query.PageSize + 1;
            //起始页
            var startIndex = (query.PageNumber - 1) * query.PageSize;
            data = data.OrderByDescending(m=>m.MessageCreateTime).Skip(startIndex).Take(query.PageSize);
            result.Data = data;
            result.TotalInfo = new TotalInfo
            {
                TotalRecouds = totalRecouds,
                TotalPages = totalPages
            };
            return result;
        }

        /// <summary>
        /// 统计信息
        /// </summary>
        /// <param name="emplId"></param>
        /// <returns></returns>
        public List<WorkflowTypeStatistics> GetWorkflowTypeStatistics(string emplId)
        {
            //返回结果
            var data = new List<WorkflowTypeStatistics>();
            //待处理
            var pending = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                           join b in _repository.All<WKF_Message>()
                           on a.MessageId equals b.MessageID
                           join c in _repository.All<WKF_MessageHandle>(m => (m.UserID == emplId || m.EntrustBy == emplId) && m.HandleStatus == 2)
                           on b.MessageID equals c.MessageID
                           select a).Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "待处理的公文",
                Count = pending
            });
            //处理过
            var dealWith = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                            join b in _repository.All<WKF_Message>()
                            on a.MessageId equals b.MessageID
                            join c in _repository.All<WKF_WorkflowHistory>(m => m.NodeKey != "NODE0001" && m.HandledBy == emplId)
                            on b.MessageID equals c.MessageID
                            select a.MessageId).Distinct().Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "已处理过的公文",
                Count = dealWith
            });
            //发出未完成
            var noComplete = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                              join b in _repository.All<WKF_Message>(m => m.MessageStatus != 2 && m.MessageIssuedBy == emplId)
                              on a.MessageId equals b.MessageID
                              select a.MessageId).Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "我发出的未完成的公文",
                Count = noComplete
            });
            //发出已完成
            var complete = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                            join b in _repository.All<WKF_Message>(m => m.MessageStatus == 2 && m.MessageIssuedBy == emplId)
                            on a.MessageId equals b.MessageID
                            select a.MessageId).Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "我发出的已完成的公文",
                Count = complete
            });
            //终止的
            var termination = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                               join b in _repository.All<WKF_Message>(m => m.MessageStatus == 3 && m.MessageIssuedBy == emplId)
                               on a.MessageId equals b.MessageID
                               select a.MessageId).Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "我终止的公文",
                Count = termination
            });
            //草稿
            var draft = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                         join b in _repository.All<WKF_Message>(m => m.MessageStatus == 0 && m.MessageIssuedBy == emplId
                                                                && m.MessageType == "file")
                         on a.MessageId equals b.MessageID
                         select a.MessageId).Count();
            data.Add(new WorkflowTypeStatistics
            {
                Name = "我的草稿",
                Count = draft
            });

            return data;
        }


        /// <summary>
        /// 待处理总数
        /// </summary>
        /// <param name="emplId"></param>
        /// <returns></returns>
        public int? TodoNumber(string emplId)
        {
            //待处理
            var pending = (from a in _repository.All<GW_ReceiveFile>(m => m.IsFirstLoading.HasValue && !m.IsFirstLoading.Value)
                           join b in _repository.All<WKF_Message>()
                           on a.MessageId equals b.MessageID
                           join c in _repository.All<WKF_MessageHandle>(m => (m.UserID == emplId || m.EntrustBy == emplId ) && m.HandleStatus != 0)
                           on b.MessageID equals c.MessageID
                           select a).Count();
            return pending;
        }
    }
}